﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace SimpleActor
{
    // internal helper class

    internal class CompiledExpressionInfo<TDelegate>
    {
        private readonly string memberName;
        private readonly Type expressionType;
        private readonly TDelegate invoke;

        public CompiledExpressionInfo(Expression<TDelegate> expression)
        {
            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }
            if (ExpressionHelper.ValueIncluded(expression))
            {
                throw new ArgumentException("expression");
            }

            memberName = ExpressionHelper.GetMemberName(expression);
            expressionType = expression.GetType();
            invoke = expression.Compile();
        }

        public string MemberName
        {
            get { return memberName; }
        }

        public Type ExpressionType
        {
            get { return expressionType; }
        }

        public TDelegate Invoke
        {
            get { return invoke; }
        }
    }

    internal class CompiledExpressionCache
    {
        private static readonly ConcurrentDictionary<object, object> Cache = new ConcurrentDictionary<object, object>();

        private static object GetKey<TDelegate>(Expression<TDelegate> expression)
        {
            var memberName = ExpressionHelper.GetMemberName(expression);
            var expressionType = expression.GetType();
            var ret = Tuple.Create(memberName, expressionType);
            return ret;
        }

        public static CompiledExpressionInfo<TDelegate> Get<TDelegate>(Expression<TDelegate> expression)
        {
            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }
            if (ExpressionHelper.ValueIncluded(expression))
            {
                throw new ArgumentException("expression");
            }

            var ret = (CompiledExpressionInfo<TDelegate>)Cache.GetOrAdd(GetKey(expression),
                        _ => new CompiledExpressionInfo<TDelegate>(expression));
            return ret;
        }
    }
}
